package rpcpool

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

type holder struct {
	host  string
	sname string
}

var rwmCmds sync.RWMutex
var cmds map[string][]holder

func init() {
	cmds = make(map[string][]holder)
}

func Bind(cmd string, host string, sname string) {
	rwmCmds.Lock()
	hs, ok := cmds[cmd]
	if ok {
		hs = append(hs, holder{host: host, sname: sname})
	} else {
		cmds[cmd] = []holder{{host: host, sname: sname}}
	}
	rwmCmds.Unlock()
}

func Call(cmd string, body []byte) (relay []byte, err error) {
	rwmCmds.RLock()
	hs, ok := cmds[cmd]
	h := hs[rand.Intn(len(hs))]
	rwmCmds.RUnlock()

	if ok {
		rpc := Get(h.host)
		if rpc == nil {
			relay = nil
			err = fmt.Errorf("rpc无法连接到目标机器:%s", h.host)
			return
		}

		closeTimerChan := make(chan bool)

		//超时检查
		go func() {
			for {
				select {
				case <-closeTimerChan:
					break
				case <-time.After(5 * time.Second):
					rpc.Close()
					Reset(h.host)
					break
				}
			}
		}()

		err = rpc.Call(h.sname+".HandleMsg", []interface{}{cmd, body}, &relay)
		closeTimerChan <- true
	}

	return
}
